<?php

namespace app\index\controller;

use think\Controller;
use app\util\Utils;
use app\v300\model\Code;
//use app\v300\model\Store;
use app\v300\model\Custom;
use think\Validate;
use think\Db;
use app\util\Easemob;
use app\index\model\Share;
use app\index\model\Store;
use app\index\model\Coupon;
use app\index\model\CtmCun;

class IndexController extends Controller {
    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 150000  
         * 150001  
         */
    }

    /*
     * 克克美协议（商户）
     * author xfwed
     * date 2017-08-18
     * http://app.dwkekemei.com/kkmnew/public/index.php/index/index/protocol
     */

    public function protocol() {
        return view('', 'protocol');
    }
    
    /*
     * 克克美协议（用户）
     * author xfwed
     * date 2017-08-18
     * http://app.dwkekemei.com/kkmnew/public/index.php/index/index/protocolyh
     */

    public function protocolyh() {
        return view('', 'protocolyh');
    }

    /*
     * 关于克克美
     * author xfwed
     * date 2017-08-18
     * http://app.dwkekemei.com/kkmnew/public/index.php/index/index/about
     */

    public function about() {
        return view('', 'about');
    }

    /*
     * 克克美提现服务申明
     * author xfwed
     * date 2017-08-21
     * http://app.dwkekemei.com/kkmnew/public/index.php/index/index/withdraw
     */

    public function withdraw() {
        return view('', 'withdraw');
    }

    /*
     * 扫描二维码  已经安装软件 直接跳转到指定店铺  没有安装软件的 跳到商店下载
     * author wxf
     * date 2016-12-26   
     */

    public function sweepcode() {
        //$this->error('请你扫码新版本二维码');
        //$path = $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        $id = input('param.id'); //店铺id
        $share_id = input('param.share_id'); //分享者id
        //返回店铺的3.8活动代金券金额
        $couponmoney = Coupon::where('store_id','=',$id)
                ->where('type','=',  5)
                ->where('issue','=',  Coupon::ISSUE_1)
                ->order('add_time desc')
                ->limit(0,2)
                ->select();
        if($couponmoney){
            $money = $couponmoney[0]['money']+$couponmoney[1]['money'];
        }  else {
            $money = 0;
        }
        return view('sweepcode', [
            'id' => $id,
            'share_id' => $share_id,
            'money' => $money,
        ]);
    }

    /*
     * 注册
     * 作者 xfwed
     * 日期 2017-10-17
     *
     * @param int custom_phone 手机号
     * @param int custom_pwd 登录密码
     * @param int code 验证码
     */

    public function register() {
        $rule = [
            'custom_phone' => 'require|length:11',
            'custom_pwd' => 'require|length:6,20',
            'code' => 'require|length:4',
            'store_id' => 'require',
        ];
        $msg = [
            'custom_phone.require' => '手机号必须',
            'custom_phone.length' => '手机号长度为11',
            'custom_pwd.require' => '密码必须',
            'custom_pwd.length' => '密码长度为6-20',
            'code.require' => '验证码必须',
            'code.length' => '验证码长度为4',
            'store_id.require' => '店铺编号必须',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::H5Return(1, $error, null);
        }

        $custom_phone = $all['custom_phone'];
        $custom_pwd = $all['custom_pwd'];
        $code = $all['code'];
        $store_id = $all['store_id'];
//        $isno = $all['isno'];
//        if ($isno == "/php-sh-v300/public/static/web/index/sweepcode/images/queren_weixuanzhong@3x.png") {
//            return Utils::H5Return(10006, '必须同意克克美服务协议', null);
//        }

        $lastRow = Code::where('type', '=', Code::TYPE_21)
                ->where('telephone', '=', $custom_phone)
                ->field('id, code, status, add_time')
                ->order('add_time desc')
                ->find();
        if (is_null($lastRow)) {
            return Utils::H5Return(10006, '未发送验证码', null);
        }

        //验证码已过期 = 超过15分钟 + 已使用 + 输入旧验证码
        $now = time();
        if (($now - $lastRow['add_time']) > 900) {
            return Utils::H5Return(10007, '验证码已过期', null);
        }
        if ($lastRow['status'] == Code::STATUS_2) {
            return Utils::H5Return(10007, '验证码已过期', null);
        }

        if ($lastRow['code'] != $code) {
            return Utils::H5Return(10008, '验证码错误', null);
        }

        $exist = Custom::where('custom_phone', '=', $custom_phone)->find();
        if (!is_null($exist)) {
            return Utils::H5Return(10009, '该手机号已经注册过，请使用克克美APP扫码', $custom_phone);
        }

        Db::startTrans();
        $custom_pwd = md5($custom_pwd);
        $custom_photo = Custom::DEFAULT_PHOTO;

        $token = Utils::generateToken();
        $share_id = input('param.share_id');
        $storedata = Store::where('id', '=', $store_id)->field('toker_switch')->find();
        if ($share_id && $storedata['toker_switch'] == 1) {
            $source = 2;
        } else {
            $source = 1;
        }

        $data = [
            'store_id' => $store_id,
            'custom_phone' => $custom_phone,
            'custom_pwd' => $custom_pwd,
            'custom_photo' => $custom_photo,
            'login_time' => $now,
            'visit_count' => 1,
            'visit_time' => $now,
            'token' => $token,
            'add_time' => $now,
            'source' => $source,
        ];
        $insertId = Custom::insertGetId($data);

        $codeResult = Code::where('id', '=', $lastRow['id'])->update(['status' => Code::STATUS_2]);

        if ($share_id && $storedata['toker_switch'] == 1) {//有分享者id 添加领取代金券记录
            $share = [
                'store_id' => $store_id,
                'share_id' => $share_id,
                'reg_id' => $insertId,
                'add_time' => time(),
            ];
            $shareid = Share::insertGetId($share);
        } else {
            $shareid = true;
        }
        if ($insertId && $codeResult && $shareid) {
            Db::commit();

            $easemob = new Easemob();
            $easemob->createUser('yh'.$custom_phone . $store_id, md5($custom_pwd));
            return Utils::H5Return(0, '注册成功', $custom_phone);
        } else {
            Db::rollback();

            return Utils::H5Return(10010, '注册失败', null);
        }
    }

    /*
     * 注册发送验证码
     * 作者 xfwed
     * 日期 2017-10-17
     *
     * @param int custom_phone 客户账号
     * @param int type 验证码类型 21注册验证码 22忘记密码验证码
     */

    public function sendCode() {
        $rule = [
            'custom_phone' => 'require|length:11',
        ];
        $msg = [
            'custom_phone.require' => '手机号必须',
            'custom_phone.length' => '手机号长度为11',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::H5Return(1, $error, null);
        }

        $custom_phone = $all['custom_phone'];

        if (!Utils::checkTelephone($custom_phone)) {
            return Utils::H5Return(10002, '请输入真实手机号', null);
        }

//        $customRow = Custom::where('custom_phone', '=', $custom_phone)->find();
//        if (!is_null($customRow)) {
//            return Utils::H5Return(10009, '该手机号已经注册过，请使用克克美APP扫码', $custom_phone);
//        }


        $canSend = Code::canSendCode($custom_phone, Code::TYPE_21);
        if (!$canSend) {
            return Utils::H5Return(10004, '验证码发送频繁', null);
        }

        $code = mt_rand(1000, 9999);
        $content = '';
        $content = '您的注册验证码是' . $code . '，验证码有效期15分钟';
        $sendResult = Utils::sendSms($custom_phone, $content);
        if ($sendResult['code'] == 'success') {
            //写入验证码
            $codeData = [
                'type' => Code::TYPE_21,
                'telephone' => $custom_phone,
                'code' => $code,
                'status' => Code::STATUS_1,
                'times' => 1,
                'add_time' => time(),
            ];

            Code::insert($codeData);

            return Utils::H5Return(0, '验证码发送成功', null);
        } else {
            return Utils::H5Return(10005, $sendResult['msg'], null);
        }
    }

    /*
     * 邀请好友规则
     * author xfwed
     * date 2018-01-12
     * http://app.dwkekemei.com/kkmnew/public/index.php/index/index/rules
     */

    public function rules() {
        return view('', 'rules');
    }

    /*
     * 红包分享
     * author xfwed
     * date 2018-02-27
     * http://app.dwkekemei.com/kkmnew/public/index.php/index/index/redpacket
     */

    public function redpacket() {
        $id = input('param.id'); //店铺id
        $share_id = input('param.share_id'); //分享者id
        return view('redpacket', [
            'id' => $id,
            'share_id' => $share_id,
        ]);
    }
    
    /*
     * 注册
     * 作者 xfwed
     * 日期 2019-03-04
     *
     * @param int custom_phone 手机号
     * @param int custom_pwd 登录密码
     * @param int code 验证码
     */

    public function newregister() {
        $rule = [
            'custom_phone' => 'require|length:11',
            'code' => 'require|length:4',
            'store_id' => 'require',
        ];
        $msg = [
            'custom_phone.require' => '手机号必须',
            'custom_phone.length' => '手机号长度为11',
            'code.require' => '验证码必须',
            'code.length' => '验证码长度为4',
            'store_id.require' => '店铺编号必须',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::H5Return(1, $error, null);
        }

        $custom_phone = $all['custom_phone'];
        $code = $all['code'];
        $store_id = $all['store_id'];
//        $isno = $all['isno'];
//        if ($isno == "/php-sh-v300/public/static/web/index/sweepcode/images/queren_weixuanzhong@3x.png") {
//            return Utils::H5Return(10006, '必须同意克克美服务协议', null);
//        }

        $lastRow = Code::where('type', '=', Code::TYPE_21)
                ->where('telephone', '=', $custom_phone)
                ->field('id, code, status, add_time')
                ->order('add_time desc')
                ->find();
        if (is_null($lastRow)) {
            return Utils::H5Return(10006, '未发送验证码', null);
        }

        //验证码已过期 = 超过15分钟 + 已使用 + 输入旧验证码
        $now = time();
        if (($now - $lastRow['add_time']) > 900) {
            return Utils::H5Return(10007, '验证码已过期', null);
        }
        if ($lastRow['status'] == Code::STATUS_2) {
            return Utils::H5Return(10007, '验证码已过期', null);
        }

        if ($lastRow['code'] != $code) {
            return Utils::H5Return(10008, '验证码错误', null);
        }

        $exist = Custom::where('custom_phone', '=', $custom_phone)->find();
        if (!is_null($exist)) {
            //return Utils::H5Return(10009, '该手机号已经注册过，请使用克克美APP扫码', $custom_phone);
            $custom_pwd = $exist['custom_pwd'];
            $custom_name = $exist['custom_name'];
            $custom_photo = $exist['custom_photo'];
            $existRow = Custom::where('store_id', '=', $store_id)
                    ->where('custom_phone', '=', $custom_phone)
                    ->field('id, store_id, custom_phone,custom_pwd, custom_name, custom_photo, vip_status, status,vippwd,visit_count')
                    ->find();
            if (is_null($existRow)) {//在本店没有注册过店铺
                $customData = [
                    'store_id' => $store_id,
                    'custom_phone' => $custom_phone,
                    'custom_pwd' => $custom_pwd,
                    'custom_name' => $custom_name,
                    'real_name' => $exist['real_name'],
                    'custom_sex' => $exist['custom_sex'],
                    'custom_birth' => $exist['custom_birth'],
                    'custom_photo' => $custom_photo,
                    'qq_openid' => $exist['qq_openid'],
                    'qq_name' => $exist['qq_name'],
                    'wx_unionid' => $exist['wx_unionid'],
                    'wx_name' => $exist['wx_name'],
                    'vippwd' => $exist['vippwd'],
                    'custom_char' => $exist['custom_char'],
                    'is_updatename' => $exist['is_updatename'],
                    'like_itemtype' => $exist['like_itemtype'],
                    'is_setshop' => $exist['is_setshop'],
                    'november_time' => $exist['november_time'],
                    'login_time' => time(),
                    'visit_time' => time(),
                    'add_time' => time(),
                ];
                $insertId = Custom::insertGetId($customData);
                if ($insertId) {
                    $easemob = new Easemob();
                    $easemob->createUser('yh' . $custom_phone . $store_id, $custom_pwd);

                    //给店铺发推送
                    $ctm_name = strlen($custom_name) > 0 ? $custom_name : $custom_phone;

                    $staffRow = Store::getStoreStaff($store_id);
                    $content = "【新客】恭喜您！店铺又迎来一名新客户 [{$ctm_name}]，赶快去安排回访吧";
                    $msgContent = Utils::getColoredString($content);
                    $pushContent = Utils::getPushString($content);
                    $alias = $staffRow['staff']['telephone'] . $store_id;
                    $userid = $staffRow['staff_id'];
                    Utils::sendServicenews(Servicenews::TITLEID_4, $insertId, 0, $msgContent, $userid, Servicenews::TYPE_1, $store_id, [
                        'title' => '新客消息',
                        'content' => $pushContent,
                        'alias_type' => Servicenews::ALIAS_TYPE_1,
                        'alias' => $alias,
                    ]);

                    $coupon_ids = Coupon::where('store_id', '=', $store_id)
                            ->where('type', '=', 5)
                            ->where('issue', '=', 1)
                            ->where('mature','>=',  time())
                            ->column('id');
                    if (count($coupon_ids) > 0) {
                        $now = time();
                        $money = 0.00;
                        for ($i = 0; $i < count($coupon_ids); $i++) {
                            $coupon_id = $coupon_ids[$i];
                            $row = Coupon::where('id', '=', $coupon_id)
                                    ->field('store_id,money, mature, number, send_number,issue')
                                    ->find();
                            if ($row['issue'] == Coupon::ISSUE_2) {
                                continue;
                                //return Utils::ajaxReturn(80007, '代金券已经删除', null);
                            }
                            if (is_null($row)) {
                                continue;
                                //return Utils::ajaxReturn(80000, '代金券不存在', null);
                            }
                            if ($row['mature'] <= $now) {
                                continue;
                                //return Utils::ajaxReturn(80001, '代金券已过期', null);
                            }
                            $exist = CtmCun::where('ctm_id', '=', $insertId)
                                    ->where('cun_id', '=', $coupon_id)
                                    ->find();
                            if (!is_null($exist)) {
                                continue;
                                //return Utils::ajaxReturn(80003, '你已经领取该代金券', null);
                            }

                            Db::startTrans();

                            $ctmCunData = [
                                'type' => 5,
                                'store_id' => $store_id,
                                'ctm_id' => $insertId,
                                'cun_id' => $coupon_id,
                                'add_time' => $now,
                                'end_time' => $now + 30 * 24 * 3600,
                            ];
                            $ctmCunResult = CtmCun::insert($ctmCunData);

                            $couponResult = Coupon::where('id', '=', $coupon_id)->setInc('send_number');
                            if ($ctmCunResult && $couponResult) {
                                Db::commit();
                            } else {
                                Db::rollback();
                            }
                        }
                        return Utils::H5Return(0, '注册成功', 1);
                    }  else {
                        return Utils::H5Return(0, '注册成功', 0);
                    }
                    
                }
            } else {//在本店注册过店铺
                $result = false;
                if ($existRow['status'] == Custom::STATUS_2) {
                    //return Utils::ajaxReturn(20001, '你已经添加过该店铺了', null);

                    $result = Custom::where('id', '=', $existRow['id'])->update([
                        'login_time' => time(),
                        'visit_time' => time(),
                    ]);
                } else {
                    $result = Custom::where('id', '=', $existRow['id'])->update([
                        'login_time' => time(),
                        'visit_time' => time(),
                        'status' => Custom::STATUS_2,
                    ]);
                }

                $coupon_ids = Coupon::where('store_id', '=', $store_id)
                        ->where('type', '=', 5)
                        ->where('issue', '=', 1)
                        ->where('mature','>=',  time())
                        ->column('id');
                if (count($coupon_ids) > 0) {
                    $now = time();
                    $money = 0.00;
                    for ($i = 0; $i < count($coupon_ids); $i++) {
                        $coupon_id = $coupon_ids[$i];
                        $row = Coupon::where('id', '=', $coupon_id)
                                ->field('store_id,money, mature, number, send_number,issue')
                                ->find();
                        if ($row['issue'] == Coupon::ISSUE_2) {
                            continue;
                            //return Utils::ajaxReturn(80007, '代金券已经删除', null);
                        }
                        if (is_null($row)) {
                            continue;
                            //return Utils::ajaxReturn(80000, '代金券不存在', null);
                        }
                        if ($row['mature'] <= $now) {
                            continue;
                            //return Utils::ajaxReturn(80001, '代金券已过期', null);
                        }
                        $exist = CtmCun::where('ctm_id', '=', $existRow['id'])
                                ->where('cun_id', '=', $coupon_id)
                                ->find();
                        if (!is_null($exist)) {
                            continue;
                            //return Utils::ajaxReturn(80003, '你已经领取该代金券', null);
                        }

                        Db::startTrans();

                        $ctmCunData = [
                            'type' => 5,
                            'store_id' => $store_id,
                            'ctm_id' => $existRow['id'],
                            'cun_id' => $coupon_id,
                            'add_time' => $now,
                            'end_time' => $now + 30 * 24 * 3600,
                        ];
                        $ctmCunResult = CtmCun::insert($ctmCunData);

                        $couponResult = Coupon::where('id', '=', $coupon_id)->setInc('send_number');
                        if ($ctmCunResult && $couponResult) {
                            Db::commit();
                        } else {
                            Db::rollback();
                        }
                    }
                    return Utils::H5Return(0, '注册成功', 1);
                }  else {
                    return Utils::H5Return(0, '注册成功', 0);
                }
                
            }
        } else {
            Db::startTrans();
            $custom_pwd = md5('dwkkm123');
            $custom_photo = Custom::DEFAULT_PHOTO;

            $token = Utils::generateToken();
            $share_id = input('param.share_id');
            $storedata = Store::where('id', '=', $store_id)->field('toker_switch')->find();
            if ($share_id && $storedata['toker_switch'] == 1) {
                $source = 2;
            } else {
                $source = 1;
            }

            $data = [
                'store_id' => $store_id,
                'custom_phone' => $custom_phone,
                'custom_pwd' => $custom_pwd,
                'custom_photo' => $custom_photo,
                'login_time' => $now,
                'visit_count' => 1,
                'visit_time' => $now,
                'token' => $token,
                'add_time' => $now,
                'source' => $source,
            ];
            $insertId = Custom::insertGetId($data);

            $codeResult = Code::where('id', '=', $lastRow['id'])->update(['status' => Code::STATUS_2]);

            if ($share_id && $storedata['toker_switch'] == 1) {//有分享者id 添加领取代金券记录
                $share = [
                    'store_id' => $store_id,
                    'share_id' => $share_id,
                    'reg_id' => $insertId,
                    'add_time' => time(),
                ];
                $shareid = Share::insertGetId($share);
            } else {
                $shareid = true;
            }
            if ($insertId && $codeResult && $shareid) {
                Db::commit();

                $easemob = new Easemob();
                $easemob->createUser('yh' . $custom_phone . $store_id, md5($custom_pwd));
                
                $coupon_ids = Coupon::where('store_id', '=', $store_id)
                        ->where('type', '=', 5)
                        ->where('issue', '=', 1)
                        ->where('mature','>=',  time())
                        ->column('id');
                if (count($coupon_ids) > 0) {
                    $now = time();
                    $money = 0.00;
                    for ($i = 0; $i < count($coupon_ids); $i++) {
                        $coupon_id = $coupon_ids[$i];
                        $row = Coupon::where('id', '=', $coupon_id)
                                ->field('store_id,money, mature, number, send_number,issue')
                                ->find();
                        if ($row['issue'] == Coupon::ISSUE_2) {
                            continue;
                            //return Utils::ajaxReturn(80007, '代金券已经删除', null);
                        }
                        if (is_null($row)) {
                            continue;
                            //return Utils::ajaxReturn(80000, '代金券不存在', null);
                        }
                        if ($row['mature'] <= $now) {
                            continue;
                            //return Utils::ajaxReturn(80001, '代金券已过期', null);
                        }
                        $exist = CtmCun::where('ctm_id', '=', $insertId)
                                ->where('cun_id', '=', $coupon_id)
                                ->find();
                        if (!is_null($exist)) {
                            continue;
                            //return Utils::ajaxReturn(80003, '你已经领取该代金券', null);
                        }

                        Db::startTrans();

                        $ctmCunData = [
                            'type' => 5,
                            'store_id' => $store_id,
                            'ctm_id' => $insertId,
                            'cun_id' => $coupon_id,
                            'add_time' => $now,
                            'end_time' => $now + 30 * 24 * 3600,
                        ];
                        $ctmCunResult = CtmCun::insert($ctmCunData);

                        $couponResult = Coupon::where('id', '=', $coupon_id)->setInc('send_number');
                        if ($ctmCunResult && $couponResult) {
                            Db::commit();
                        } else {
                            Db::rollback();
                        }
                    }
                    return Utils::H5Return(0, '注册成功', 1);
                }  else {
                    return Utils::H5Return(0, '注册成功', 0);
                }
                
            } else {
                Db::rollback();

                return Utils::H5Return(10010, '注册失败', null);
            }
        }
    }
    
    /*
     * 注册成功跳转空页面 
     * 浏览器打开
     * 进入app或者appstore
     * author xfwed
     * date 2019-03-04
     */

    public function openapp() {
        $id = input('param.id'); //店铺id
        $phone = input('param.phone'); //手机号
        return view('openapp', [
            'id' => $id,
            'phone' => $phone,
        ]);
    }
    
    /*
     * 微信分享需要的参数
     * author xfwed
     * date 2019-03-04
     */
    public function wxshare(){
        $pic = '';
        $title = '';
        $description = '';
        $currentUrl = input('param.currentUrl');
        $weixindata = Utils::Wxshare($pic,$title,$description,$currentUrl);
        return json_encode($weixindata);
    }

}
